import axios from 'axios';

// 事件总线
export class EventBus {
  events: object = {};
  constructor() {
    this.events = {};
  }

  on(name: string, callback) {
    // 订阅
    this.events[name] = callback;
  }
  emit(name: string, ...args: any[]) {
    // 发布
    this.events[name]?.(...args);
  }
}

// 组件通用模型
export class Model extends EventBus {
  status: number = 0; // 状态 0 未开始 1 加载中 2 成功 3 失败
  response: object = {}; // 响应数据
  config: ProxyConfig; // 配置
  proxy: AxiosProxy; // 代理
  error: Error | null | unknown = null; // 错误
  constructor(config: ProxyConfig) {
    super();
    this.proxy = new AxiosProxy(config, this);
    this.config = config;
  }
  async load(params?: object) {
    this.status = 1;
    try {
      const data = await this.proxy.readData(params);
      console.log(data, 'data');
      this.status = 2;
    } catch (error) {
      this.status = 3;
      this.error = error;
    }
  }
}

// axios代理
export class AxiosProxy {
  config: ProxyConfig;
  store: any;
  cancel: any;
  reader: any;
  constructor(config: ProxyConfig, store) {
    const { reader, ...axiosConfig } = config;
    this.reader = reader;
    this.config = axiosConfig;
    this.store = store;
    this.cancel = null;
  }

  abort() {
    this?.cancel();
  }
  async readData(params?: object) {
    let res = await axios({
      ...this.config,
      params,
      cancelToken: new axios.CancelToken(c => {
        this.cancel = c;
      })
    });
    this.store.emit('response', res);
    if (this.reader) {
      res = this.reader(res);
      this.store.emit('data', res);
    } else {
      this.store.emit('data', res);
    }
    return res;
  }
}

const store = new Model({
  url: '/mock/api/login',
  reader(res) {
    return res.data;
  }
});

store.on('data', data => {
  console.log(data);
});

store.load();
